package cn.xchats.rpc.client.load;

import cn.xchats.rpc.common.util.PropertyUtil;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/*
 *
 *@author teddy
 *@date 2018/7/6
 */
@Component
public class LoadBalanceConfig {

    public static final List<String> serverAddressList = new ArrayList<>();

    public LoadBalanceConfig() {
    }
    static {
        initConfig();
    }

    private static void initConfig() {
        String addressList;
        //加载服务端的连接地址
        addressList = PropertyUtil.getProperty("tcp.server.address");
        if (null == addressList) {
            throw new NullPointerException("init error : tcp server address is not find");
        }

        String[] addressArray = addressList.split(",");
        for (int i = 0; i < addressArray.length; i++) {
            serverAddressList.add(addressArray[i]);
        }
    }

    /**
     * 获取服务器的ip
     */
    public static String getServerHost(int index) {
        String serverHost;
        String serverAddress;
        serverAddress = serverAddressList.get(index);
        if (null == serverAddress)
            return null;
        String[] serverAddressSplit = serverAddress.split(":");
        if (2 != serverAddressSplit.length)
            return null;
        serverHost = serverAddressSplit[0];
        return serverHost;
    }

    /**
     * 获取服务器的port
     */
    public static int getServerPort(int index) {
        String serverPort;
        String serverAddress;
        serverAddress = serverAddressList.get(index);
        if (null == serverAddress)
            return -1;
        String[] serverAddressSplit = serverAddress.split(":");
        if (2 != serverAddressSplit.length)
            return -1;
        serverPort = serverAddressSplit[1];
        return Integer.valueOf(serverPort);
    }

    public int select(){
        return -1;
    }
}
